﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Webapi.EFCore.Model;
using Webapi.EFCore.Model.Enity;
using Webapi.EFCore.Model.EFCodeFirst;

/// <summary>
/// EF 上下文
/// </summary>
public class EFCoreDbContext : DbContext
{
    public EFCoreDbContext(DbContextOptions<EFCoreDbContext> options)
     : base(options)
    {
    }
    /// <summary>
    /// 配置注入
    /// </summary>
    /// <param name="optionsBuilder"></param>
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        //optionsBuilder.UseInternalServiceProvider()            
        //string connection = "";
        //如果字符串不为空，就注入链接字符串
        //if (!string.IsNullOrEmpty(BaseDBConfig.ConnectionString))
        //    optionsBuilder.UseSqlServer(BaseDBConfig.ConnectionString);
        //optionsBuilder.UseSqlServer(optionsBuilder.Options.Extensions.)          

        //this.Database.SetCommandTimeout(60);

        //设置不跟踪所有查询  2019-8-4 15:24:33 add
        //optionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);

        //参数记录 2019-8-4 15:24:33 add
        //optionsBuilder.EnableSensitiveDataLogging();

        //var loggerFactory = new LoggerFactory();
        //  loggerFactory.AddProvider(new ConsoleLoggerProvider((category, level)
        //=> category == DbLoggerCategory.Database.Command.Name
        //   && level == LogLevel.Information, true));

        //记录sql生成
        //loggerFactory.AddDebug(
        //    (categoryName, logLevel) =>
        //    //(logLevel == LogLevel.Debug) && (categoryName == DbLoggerCategory.Database.Command.Name)
        //    logLevel == LogLevel.Information
        //    && categoryName == DbLoggerCategory.Database.Command.Name
        //    //|| (categoryName == DbLoggerCategory.Query.Name)
        //    //|| (categoryName == DbLoggerCategory.Model.Name)
        //    );

        //optionsBuilder.UseLoggerFactory(loggerFactory);
    }

    /// <summary>
    /// 关系映射
    /// </summary>
    /// <param name="modelBuilder"></param>
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //modelBuilder.Entity<User>().Property<string>("TenantId").HasField("_tenantId");
        //Configure entity filters
    }

    #region 导航属性

    public virtual DbSet<User> User { get; set; }

    //下面写更多个上下文

    #endregion

}


